package snsdbook.engine.message;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import snsdbook.engine.FileManager;
import util.SQLUtil;
import util.Util;

public class LoginRequestMessage implements MessageInterface {

  private static final long serialVersionUID = 8665947662019052316L;

  public LoginRequestMessage(String username, String password) {
    username_ = username;
    password_ = password;
  }
  
  private String username_;
  private String password_;
  
  @Override
  public String ProcessAsServer(ObjectInputStream is, ObjectOutputStream os) {
    Util.Log("Attempting to verify username and password for " + username_);
    String[] pass = SQLUtil.Query("SELECT password FROM users WHERE username='" + username_ + "'");
    MessageInterface reply = null;
    if (pass.length != 1 || !pass[0].equals(password_)) {
      // Fail
      Util.Log("Username and/or Password is wrong");
      reply = new LoginReplyMessage("FAIL");
    } else {
      // Fail
      Util.Log("Username and/or Password is correct");
      reply = new LoginReplyMessage("OK");
    }
    
    reply.ProcessAsServer(is, os);
    Util.Log("Reply sent");
    return "";
  }

  @Override
  public String ProcessAsClient(ObjectInputStream is, ObjectOutputStream os,
                                FileManager manager) {
    Util.Send(os, this);
    return Util.Receive(is).ProcessAsClient(is, os, manager);
  }
  
  @Override
  public String toString() {
    return "LOGIN REQUEST MESSAGE, USERNAME=" + username_;
  }

}
